﻿using Autofac;
using Pay.DTO;
using Pay.IService;
using Pay.Service;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Pay.Distribution.Controllers {

    public class MerchantController : GeneralController {
        private IMerchantService _iMerchantService;
        private ISettingService _iSettingService;
        private IComponentContext _iocContext;
        private IRoleService _iroleService;
        private IManageService _imanageService;

        public MerchantController(IComponentContext iocContext, IMerchantService iMerchantService, ISettingService iSettingService, IRoleService roleService, IManageService manageService) {
            _iocContext = iocContext;
            _iMerchantService = iMerchantService;
            _iSettingService = iSettingService;
            _iroleService = roleService;
            _imanageService = manageService;
        }

        public ActionResult Index() {
            return View();
        }
        public JsonResult GetRoleList() {
            var list = _iroleService.GetAll();
            return Json(ResultToJson.Json(list), JsonRequestBehavior.AllowGet);
        }
        public JsonResult Gets(MerchantQuery query) {
            var merchant = _iMerchantService.Get(currentUser.user_id);
            if (merchant != null && merchant.is_oem == true)
                query.parent_id = currentUser.user_id;
            var model = _iMerchantService.GetMerchant(query);
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetOem() {
            var model = _iMerchantService.GetOems();
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Get(long id) {
            var model = _iMerchantService.GetMerchant(id);
            var role = _imanageService.GetRole(model.id);
            if (role != null)
                model.roleid = role.id;
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult Add(register_model dto) {
            dto.parent_no = _iMerchantService.Get(currentUser.user_id).merchant_no;
            if (dto.role_id == 5)
                dto.is_supplier = true;
            var result = _iMerchantService.Register(dto);
            var manage = new manage_dto();
            manage.role_id = dto.role_id;
            manage.merchant_id = result.id;
            manage.mobile = dto.mobile;
            manage.nick = dto.name;

            // manage.
            var temp = _imanageService.Add(manage);
            return Json(ResultToJson.Json(temp > 0 ? "权限添加成功" : "权限添加失败"), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult ChangePwd(forget_model model) {
            _iSettingService.ValidCode(model.mobile, model.code, "fotget");
            var result = _iMerchantService.Forget(model);
            if (result)
                _iSettingService.RemoveCode(model.mobile, "fotget");
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult Update(merchant_info dto) {
            var role = _imanageService.GetManage(dto.id);
            var manage = new manage_dto();
            manage.role_id = dto.roleid;
            manage.merchant_id = dto.id;
            manage.mobile = dto.mobile;
            manage.nick = dto.name;

            if (role == null) {
                if (dto.roleid > 0) {
                    _imanageService.Add(manage);
                }
            } else {
                manage.id = role.id;
                _imanageService.Update(manage);
            }
            var user = _iMerchantService.GetMerchant(dto.id);
            if (!string.IsNullOrEmpty(dto.parent_no)) {
                var parent = _iMerchantService.Get(dto.parent_no);
                if (parent == null)
                    return Json(ResultToJson.Json<int>("上级商户不存在"), JsonRequestBehavior.AllowGet);
                if (user.parent_id != parent.id) {
                    dto.parent_id = parent.id;
                }
            } else
                dto.parent_id = 0;
            int result = _iMerchantService.Update(dto);
            return Json(ResultToJson.Json(result > 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
        }

        [HttpDelete]
        public JsonResult Detele(long id) {
            int result = _iMerchantService.Delete(id);
            return Json(ResultToJson.Json(result > 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Disable(long id, bool disabled) {
            var user = _iMerchantService.GetMerchant(id);
            user.disabled = disabled;
            int result = _iMerchantService.Update(user);
            return Json(ResultToJson.Json(result > 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 审核认证
        /// </summary>
        /// <returns>The audit.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="auth_info">Auth info.</param>
        /// <param name="status">Status.</param>
        /// <param name="msg">Message.</param>
        [HttpPost]
        public async Task<JsonResult> Audit(long id, auth_info_setting auth_info, AuthStatusEnum status, string msg) {
            int result = await _iMerchantService.Auth(id, auth_info, status, msg);
            return Json(ResultToJson.Json(result >= 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 审核认证
        /// </summary>
        /// <returns>The audit.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="status">Status.</param>
        /// <param name="msg">Message.</param>
        [HttpPost]
        public async Task<JsonResult> WXAudit(long id, AuthStatusEnum status, string msg) {
            int result = await _iMerchantService.AuthNative(id, status, msg);
            return Json(ResultToJson.Json(result >= 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改认证资料
        /// </summary>
        /// <returns>The audit.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="auth_info">Auth info.</param>
        [HttpPost]
        public async Task<JsonResult> AuthEdit(long id, auth_info_setting auth_info) {
            int result = await _iMerchantService.AuthEdit(id, auth_info);
            return Json(ResultToJson.Json(result >= 0 ? " 修改认证资料成功" : "修改认证资料失败", result), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询认证资料
        /// </summary>
        /// <returns>The register del.</returns>
        /// <param name="id">Identifier.</param>
        public JsonResult AuthList(MemberQuery query) {
            var list = _iMerchantService.Get(query);
            return Json(ResultToJson.Json(list), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 商户进件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> AddMerchant(long id, PayChannel pay_channel, string settle_type, string account_no) {
            var binder = _iMerchantService.Get(id);
            merchant_register_model model = null;
            var _iPayService = _iocContext.ResolveKeyed<IPayService>(pay_channel);
            var oemer = _iMerchantService.Get(binder.oem_id.Value);
            var oemer_payments = _iMerchantService.GetPayments(oemer.id);
            var oem_payment = oemer_payments.FirstOrDefault(c => c.payment.channel == pay_channel && c.payment.is_register);
            if (oem_payment != null) {
                var binder_registers = _iMerchantService.GetRegisters(binder.id);
                //判断是否进件过了
                merchant_register_dto register = null;
                if (oem_payment.payment.is_more)
                    register = binder_registers.FirstOrDefault(c => c.pay_channel == pay_channel && c.settle_type == settle_type && c.account_no == account_no);
                else
                    register = binder_registers.FirstOrDefault(c => c.pay_channel == pay_channel && c.settle_type == settle_type);
                string opt = "A";
                if (register != null) {
                    opt = "M";
                    model = register.ToDtoObject<merchant_register_model>();
                    model.reg_merchant_no = register.merchant_no;
                } else {
                    model = binder.setting.auth_info.ToDtoObject<merchant_register_model>();
                    if (pay_channel == PayChannel.HxData) {
                        model.reg_merchant_no = binder.merchant_no;
                        model.reg_mobile = 130 + DtoHelper.RandCode(8);
                    }
                }
                model.pay_channel = pay_channel;
                model.settle_type = settle_type;
                model.bind_no = binder.merchant_no;
                model.merchant_no = oemer.merchant_no;

                var binder_payments = _iMerchantService.GetPayments(binder.id);
                var payment = binder_payments.FirstOrDefault(c => c.payment.channel == pay_channel && c.payment.is_register);
                var settle = payment.settles.FirstOrDefault(c => c.settle_type == settle_type);
                model.fee = settle.fee;
                model.settle = ((int)(settle.settle * 100)).ToString();
                var result = await _iPayService.MerchantRegister(model, opt);
                if (result.result_code == 1000) {
                    _iMerchantService.MerchantChannelRegister(model);
                    return Json(ResultToJson.Json("保存成功", result.merchant_no), JsonRequestBehavior.AllowGet);
                }
                return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
            }
            return Json(ResultToJson.Json<string>("oem商户没有开通"), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 用实名数据进件
        /// </summary>
        /// <returns>The register.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="pay_channel">Pay channel.</param>
        /// <param name="settle_type">Settle type.</param>
        /// <param name="op">Op.</param>
        public async Task<JsonResult> AuthRegister(long id, PayChannel pay_channel, string settle_type, string op) {
            var binder = _iMerchantService.Get(id);
            var binder_payments = _iMerchantService.GetPayments(id);
            var binder_registers = _iMerchantService.GetRegisters(id);
            merchant_register_result result = null;
            var _iPayService = _iocContext.ResolveKeyed<IPayService>(pay_channel);
            if (binder_payments.Any(c => c.payment.channel == pay_channel && c.payment.is_more))
                return Json(ResultToJson.Json("多进件模式不可以用实名提交", result.merchant_no), JsonRequestBehavior.AllowGet);

            if (binder_registers.Any(c => c.pay_channel == pay_channel && c.settle_type == settle_type) || (!string.IsNullOrEmpty(op) && op == "M"))
                result = await _iPayService.MerchantModify(id, settle_type);
            else
                result = await _iPayService.MerchantRegister(id, settle_type);
            if (result.result_code == 1000)
                return Json(ResultToJson.Json("保存成功", result.merchant_no), JsonRequestBehavior.AllowGet);
            return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除进件
        /// </summary>
        /// <returns>The register del.</returns>
        /// <param name="id">Identifier.</param>
        public JsonResult auth_register_del(long id) {
            var result = _iMerchantService.DeleteMerchantRegister(id);
            if (result > 0)
                return Json(ResultToJson.Json<bool>("删除成功", result > 0), JsonRequestBehavior.AllowGet);
            return Json(ResultToJson.Json<bool>("删除失败"), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 验证实名
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<JsonResult> CertifyVerifyed(long id) {
            var merchant = _iMerchantService.Get(id);
            var model = merchant.setting.auth_info;
            var oemer = _iMerchantService.Get(merchant.oem_id.Value);
            var certify = _iSettingService.Get().certify;
            var cer = certify.FirstOrDefault(c => c.merchant_no == oemer.merchant_no);
            if (merchant.auth_status == AuthStatusEnum.Wait) {
                var reqData = new certify_verify {
                    merchant_no = oemer.merchant_no,
                    amount = cer.amount,
                    bank_code = model.bank_code,
                    account_name = model.account_name,
                    account_no = model.account_no,
                    id_card = model.id_card,
                    verify_type = "0030",
                    mobile = model.mobile,
                    bind_no = merchant.merchant_no,
                    card_type = 1,
                    order_no = DateTime.Now.ToString("yyyyMMddHHmmssffff") + DtoHelper.RandCode(6),
                    pay_channel = cer.pay_channel
                };
                var iPayService = _iocContext.ResolveKeyed<IPayService>(cer.pay_channel);
                var api_result = await iPayService.CertifyVerify(reqData);
                if (api_result.result_code == 1000)
                    return Json(ResultToJson.Json("实名成功", true), JsonRequestBehavior.AllowGet);
                return Json(ResultToJson.Json<bool>(api_result.result_msg), JsonRequestBehavior.AllowGet);
            }
            return Json(ResultToJson.Json<bool>("OEM没有开通实名"), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取当前用户下级
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public JsonResult Inferiors(MerchantQuery query) {
            var model = _iMerchantService.GetMerchant(query);
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查看商户下级菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult SearchLower(long id) {
            var result = _iMerchantService.GetOneChild(id);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }
    }
}